package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.constants.PeriodContants;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.MySHAService;

@Singleton
public class YuiCombServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private MySHAService shaService;
	
	@Inject
	private AppUtilService autils;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		//?3.4.1/build/yui-base/yui-base-min.js&3.4.1/build/oop/oop-min.js//顺序相关。
		StringBuffer qsbuf = new StringBuffer();
		String qs = req.getQueryString();//调试模式下是null，服务器一侧不可能null。
		String version = req.getParameter("version");
		String type = req.getParameter("type");
		String prefix = req.getParameter("prefix");
		String postfix = req.getParameter("postfix");
		String separator = req.getParameter("separator");
		if(separator == null || separator.isEmpty())separator="|";
		String[] fns = new String[]{};
		
		if(qs != null)
			fns = qs.split("&");
		for(String fn :fns){
			if(fn.startsWith("hostname=") || fn.startsWith("remoteip=")){
				;
			}else{
				qsbuf.append(fn).append("&");
			}
		}
		String finalqs = qsbuf.toString();
		
		if(finalqs.isEmpty()){//在混合請求的情況下，如果缺少某個組件，yui會自動拉去，這個情況下前綴也是yuicombo
			finalqs = req.getRequestURI().replace("/yuicombo", "/yui");
			fns = new String[]{finalqs};
		}
		
		//client cache 针对url而定，那么只要url不同，cache就不会hit
		//如果某个url带有version字段，那么作者必须知道这个内容的变化，所以可以永久缓存。
		if("css".equals(type)){
			type = "text/css";
		}else if("js".equals(type)){
			type = "text/javascript";
		}else{
			;
		}
		if(type == null || type.isEmpty())type = "text/javascript";
		res.setContentType(type + ";charset=utf-8");   
		res.setCharacterEncoding("UTF-8");
		if(version == null || version.isEmpty()){
			;
		}else{
			String etag = req.getHeader("If-None-Match");
			if(etag != null && etag.equals(shaService.encrypt(finalqs))){
				res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				return;
			}
			res.setHeader("Cache-Control","max-age=" + PeriodContants.YEAR_IN_SECONDS * 10);
			res.setHeader("Etag", shaService.encrypt(finalqs));
		}
		Writer out = res.getWriter();
		

		File wr = new File(getServletContext().getRealPath("/"));
		boolean separatorReached = false;
		for(String fn : fns){
			 if(fn.startsWith("type=") || fn.startsWith("prefix=") || fn.startsWith("postfix=") || fn.startsWith("separator=") || fn.startsWith("version=")){
				 continue;
			 }
			if(fn.equals(separator)){
				separatorReached = true;
				continue;
			}
			File f = null;
			if(!separatorReached){
				if(prefix != null && !prefix.isEmpty()){
					fn = prefix + fn;
				}
				if(postfix != null && !postfix.isEmpty() && !fn.endsWith(postfix)){
					fn = fn + postfix;
				}
			}
			f = new File(wr,fn);
			if(f != null && f.isFile() && f.exists()){
				try {
					FileInputStream is = new FileInputStream(f);
					out.write(autils.read2String(is, "utf-8"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		out.flush();
		out.close();
	}
}
